<?php

namespace Modules\ShopAdmin\Models;
use Modules\AuthAdmin\Services\QueryService;
class ShopProductAttrbuteKey extends BaseApiModel
{
	/**
	 * @name  关联商品分类表   多对一
	 */
	 public function product_type_to()
    {
        return $this->belongsTo('Modules\ShopAdmin\Models\ShopProductType','product_type_id','id');
    }
	/**
	 * @name  关联商品属性值   一对多
	 */
	 public function attrbute_value_to()
    {
        return $this->hasMany('Modules\ShopAdmin\Models\ShopProductAttrbuteValue','attrbute_key_id','id');
    }
	/**
     * @name   状态0和1修改为true或false
     * @param  int  $value
     * @return Boolean 
     */
    public function getStatusAttribute($value)
    {
        return $value==1?true:false;
    }
	/**
     * @name   更新时间为null时返回
     * @param  int  $value
     * @return Boolean 
     */
    public function getUpdatedAtAttribute($value)
    {
        return $value?$value:'';
    }
	/**
	 * @name  列表数据
	 * @param  data  array 搜索数据
	 * @return json 
	 */
    public function list_data($data){
		$model = $this->query();
		$model = (new QueryService())->query_condition($model,$data,'name');
		if(isset($data['product_type_id']) && $data['product_type_id']>0){
			$model = $model->where('product_type_id',$data['product_type_id']);
		}	
        $list = $model->select('id','name','product_type_id','status','created_at','updated_at','sort')
				->with([
					'product_type_to'=>function($query){
							$query->select('id','title');  
					}
				])
				->orderBy('sort','asc') 
				->orderBy('id','desc') 
				->paginate($data['pagesize'])
				->toArray(); 
		return $this->api_success(['data'=>[
			'list'=>$list['data'],
			'total'=>$list['total']
		]]);		
	}
	/**
	 * @name  获取属性
	 * @param  product_type_id int 商品分类id
	 * @return json 
	 */
    public function product_attrbute_key_list($product_type_id){
        $list = $this->select('id','name')
				->with([
					'attrbute_value_to'=>function($query){
							$query->select('id','attrbute_key_id','value');  
					}
				])
				->where('product_type_id',$product_type_id)
				->orderBy('sort','asc') 
				->orderBy('id','desc') 
				->get()
				->toArray(); 
		foreach($list as $k=>$v){
			foreach($list[$k]['attrbute_value_to'] as $k1=>$v1){
				$list[$k]['attrbute_value_to'][$k1]['checked'] = false;
			}
		}		
		return $this->api_success(['data'=>$list]);		
	}
}
